﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using UCL;
using UCL.Data;
using UCL.Forms;

namespace DBKit5.UControls
{
    /// <summary>
    /// 增删改查命令编辑界面
    /// </summary>
    /// <remarks>2014-1-21 by sutroon</remarks>
    public partial class frmCURDForm : Form
    {
        public string TableName { get; set; }
        public IDatabaseHelper DBH { get; set; }
        public Action<string> AnalyseHandler { get; set; }
        public Action<string, bool> ExecSqlHandler { get; set; }
        public frmCURDForm()
        {
            InitializeComponent();

            tbSqlSelect.ContextMenuStrip = cmsCURD;
            tbSqlInsert.ContextMenuStrip = cmsCURD;
            tbSqlDelete.ContextMenuStrip = cmsCURD;
            tbSqlUpdate.ContextMenuStrip = cmsCURD;

            tabcMain.SelectedIndexChanged += new EventHandler(tabcMain_SelectedIndexChanged);
            cmiClickConfig();
        }

        private void frmCreateForm_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(this.TableName)) this.Text = "增删改查(CURD) - " + this.TableName;
            tipInsertFormat.Text = string.Format("批量生成规则：{0}如：UserName字段从user01生成到user99，格式为：user{{int:01to99}}{0}Birthday字段从1960-1-1生成到2013-6-8，格式为：{{date:1960-1-1to2013-6-8}}{0}Birthday字段从1960-1-1到2013-6-8随机生成，格式为：{{rnd:date:1960-1-1to2013-6-8}}{0}IsOnline字段随机值为0或1，格式为：{{rnd:0,1}}{0}VipLevel字段随机值为{{1,2,3,4,5}}，格式为：{{rnd:1,2,3,4,5}}", Environment.NewLine);
            this.FormLoad();
        }

        public void FormLoad()
        {
            IList<string> fields = DBH.SO_GetFields(this.TableName);
            tbFields.Text = fields.ToString(", ");
            tbSqlDelete.Text = string.Format("delete from {0} where ...", this.TableName);
            tbSqlSelect.Text = string.Format("select top 100 {0} from {1} where ... order by ...", tbFields.Text, this.TableName);
            tbSqlInsert.Text = string.Format("insert into {0} ({1}) values ({2})", this.TableName, tbFields.Text, fields.ToString(",", "'{0}'"));
            tbSqlUpdate.Text = string.Format("update {0} set {1} where ...", this.TableName, fields.ToString(",", "{0}='{0}'"));
        }

        // 右键菜单点击事件配置
        private void cmiClickConfig()
        {
            cmi查询1000条ToolStripMenuItem.Click += new EventHandler(cmi_Click);
            cmi查询1条ToolStripMenuItem.Click += new EventHandler(cmi_Click);
            cmi查询5条ToolStripMenuItem.Click += new EventHandler(cmi_Click);
            cmi清除条件ToolStripMenuItem.Click += new EventHandler(cmi_Click);
            cmi复制ToolStripMenuItem.Click += new EventHandler(cmi_Click);
            cmi剪切ToolStripMenuItem.Click += new EventHandler(cmi_Click);
            cmi清空ToolStripMenuItem.Click += new EventHandler(cmi_Click);
            cmi全选ToolStripMenuItem.Click += new EventHandler(cmi_Click);
            cmi粘帖ToolStripMenuItem.Click += new EventHandler(cmi_Click);
        }
        // 右键菜单点击事件处理方法
        private void cmi_Click(object sender, EventArgs e)
        {
            TextBox tb = null;
            switch (tabcMain.SelectedTab.Name)
            {
                case "tp查询":
                    tb = tbSqlSelect;
                    break;
                case "tp删除":
                    tb = tbSqlDelete;
                    break;
                case "tp修改":
                    tb = tbSqlUpdate;
                    break;
            }
            if (tb == null) return;
            switch (((ToolStripMenuItem)sender).Name)
            {
                case "cmi查询1000条ToolStripMenuItem":
                    if (DBH == null || tb.TextLength == 0) return;
                    tb.Text = DBH.SQL_SetLimit(tb.Text, 1000);
                    break;
                case "cmi查询1条ToolStripMenuItem":
                    if (DBH == null || tb.TextLength == 0) return;
                    tb.Text = DBH.SQL_SetLimit(tb.Text, 1);
                    break;
                case "cmi查询5条ToolStripMenuItem":
                    if (DBH == null || tb.TextLength == 0) return;
                    tb.Text = DBH.SQL_SetLimit(tb.Text, 5);
                    break;
                case "cmi清除条件ToolStripMenuItem":
                    if (tb.TextLength == 0) return;
                    if (tb.Name == tbSqlSelect.Name)
                    {
                        if (tb.Text.EndsWith("where ... order by ...")) tb.Text = tb.Text.Substring(0, tb.TextLength - "where ... order by ...".Length);
                    }
                    else
                    {
                        if (tb.Text.EndsWith("where ...")) tb.Text = tb.Text.Substring(0, tb.TextLength - "where ...".Length);
                    }
                    break;
                case "cmi复制ToolStripMenuItem":
                    tb.Copy();
                    break;
                case "cmi剪切ToolStripMenuItem":
                    tb.Cut();
                    break;
                case "cmi清空ToolStripMenuItem":
                    tb.Clear();
                    break;
                case "cmi全选ToolStripMenuItem":
                    tb.SelectAll();
                    break;
                case "cmi粘帖ToolStripMenuItem":
                    tb.Paste();
                    break;
            }
        }

        private void btnAnalyse_Click(object sender, EventArgs e)
        {
            string sql = GetSql();
            if (sql.Length == 0) return;
            if (AnalyseHandler != null) AnalyseHandler(sql);
        }

        private void btnExec_Click(object sender, EventArgs e)
        {
            string sql = string.Empty;
            switch (this.tabcMain.SelectedTab.Name)
            {
                case "tp查询":
                    sql = tbSqlSelect.Text;
                    break;
                case "tp删除":
                    sql = tbSqlDelete.Text;
                    break;
                case "tp新增":
                    sql = tbSqlInsert.Text;
                    break;
                case "tp修改":
                    sql = tbSqlUpdate.Text;
                    break;
            }
            if (sql.Length == 0) return;
            if (ExecSqlHandler != null) ExecSqlHandler(sql, false);
        }
        private string GetSql()
        {
            if (!CheckForm()) return string.Empty;
            StringBuilder sbSql = new StringBuilder();
            int limit = tbLimit.Text.ToInt();
            if (limit > 1)
            {
                string v = tbSqlInsert.Text;
                while (limit > 0)
                {
                    if (v.Contains('{'))
                    {
                        // 替换循环变量
                    }
                    sbSql.AppendFormat("{3}insert into {0} ({1}) values ({2});", this.TableName, tbFields.Text, v);
                    limit--;
                }
            }
            else
            {
                sbSql.AppendFormat("insert into {0} ({1}) values ({2});", this.TableName, tbFields.Text, tbSqlInsert.Text);
            }
            return sbSql.ToString();
        }

        private bool CheckForm()
        {
            StringBuilder sbErr = new StringBuilder();
            if (tbFields.TextLength == 0 || tbSqlInsert.TextLength == 0) sbErr.AppendLine("字段未填写");
            if (sbErr.Length > 0)
            {
                MessageBox.Show(sbErr.ToString());
                return false;
            }
            return true;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            this.FormLoad();
        }

        private void tabcMain_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabcMain.SelectedIndex == -1) return;
            switch (tabcMain.SelectedTab.Name)
            {
                case "tp查询":
                    cmi查询1000条ToolStripMenuItem.Visible = true;
                    cmi查询1条ToolStripMenuItem.Visible = true;
                    cmi查询5条ToolStripMenuItem.Visible = true;
                    break;
                default:
                    cmi查询1000条ToolStripMenuItem.Visible = false;
                    cmi查询1条ToolStripMenuItem.Visible = false;
                    cmi查询5条ToolStripMenuItem.Visible = false;
                    break;
            }
        }
    }
}
